﻿//loadInput would load the current page and take the HTML.  This has been replace with a javascript grab of the current page.
/*function loadInput():void {
var loaderHTML:URLLoader=new URLLoader;
loaderHTML.load(new URLRequest(pageURL));
loaderHTML.addEventListener(Event.COMPLETE,HTMLloaded);
}
function HTMLloaded(event:Event):void {
htmlText = event.target.data;
slidingSetup (CategoriesArray["Results"].position);
toolChosen();
NavigateToURLcss();
}*/
function HTMLloaded2() {
	if (allOptions["defaultTool"]=="List Words") ListTools.selectedIndex=0;
	else if (allOptions["defaultTool"]=="Word Cloud") ListTools.selectedIndex=1;
	toolChosen();
}
function NavigateToURLcss():void {
		CategoriesArray["Results"].title = "Results";
		Results.catBar.catTXT.text=CategoriesArray["Results"].title;
		if (Results.backg.contains(cloudField1)) Results.backg.removeChild(cloudField1);
		if (Results.backg.contains(concordanceField)) Results.backg.removeChild(concordanceField);
		if (Results.backg.contains(sb)) Results.backg.removeChild(sb);
		
		catBgVisibility(true);
		if (ListTools.selectedItem.label!="Get Concordance" && ListTools.selectedItem.label!="Collocating Words" && ListTools.selectedItem.label!="List Words" && ListTools.selectedItem.label!="Word Cloud" && ListTools.selectedItem.label!="New Collocates") {

			var url:String=ListTools.selectedItem.url;

			if (ListTools.selectedItem.label=="Visual Collocation") {
				variables.pattern="";
				variables.context="";
				variables.contextlength="";
				if (sortCrit) {
					variables.sorting=sortCrit.selectedItem.code;
				} else {
					variables.sorting=defaultSortCrit;
				}
			}
			if (ListTools.selectedItem.label=="Old Collocating Words") {
				variables.sorting="3";
			}
			if (ListTools.selectedItem.label=="Old List Words"||ListTools.selectedItem.label=="Old Word Cloud") {
				variables.outFormat="2";
				if (ListOp) {
					variables.listOption=ListOp.selectedItem.code;
				} else {
					variables.listOption='stop';
				}
				if (sortCrit) {
					variables.sorting=sortCrit.selectedItem.code;
				} else {
					variables.sorting=defaultSortCrit;
				}
				if (stopList) {
					variables.optionSeletion=stopList.text;
				} else {
					variables.optionSeletion=allOptions["stopList"];
				}
			}
			if (ListTools.selectedItem.label=="Old Word Cloud") {
				variables.sorting="1";
			}
			if (ListTools.selectedItem.label=="Old Collocating Words"||ListTools.selectedItem.label=="Old Get Concordance") {
				variables.outFormat="xml";
				if (patternSelect.text) {
					variables.pattern=patternSelect.text;
					trace(patternSelect.text);
				} else {
					variables.pattern=defaultPattern;
				}
				variables.context=defaultContext;
				variables.contextlength=defaultContextLength;
			}
			if (htmlTagSelect) {
				variables.htmlTag=htmlTagSelect.text;
			} else {
				variables.htmlTag=allOptions["htmlTag"];
			}
			variables.htmlInput=unescape(htmlText);
			variables.toolOrigin = "FlashTAT";
			
			var request:URLRequest=new URLRequest(url);
			request.method=URLRequestMethod.POST;
			request.data=variables;

			var loader:URLLoader=new URLLoader  ;
			loader.load(request);
			//trace ("loader.load worked");
			loader.addEventListener(Event.COMPLETE,processData);
			//trace ("loader.addEventListener worked");
		} 
		else {
			if (currentCat==CategoriesArray["Results"].position) {
				if (htmlText == "Error") {//for testing... best to remove this in the long run
					htmlText = "Error.";
				}
				var wordSplit=cleanTags(unescape(htmlText));
				wordSplit=splitWords(wordSplit);
				var allWords:Object = new Object();
				allWords.words = []; //all words, in order but without repetition
				allWords.orderedArray = []; //all words, in order

				allWords.count = { }; //counts of occurrances for each word
				allWords.indexCounts = { };//arrays of orderedArray locations for each word

				var stopList:Object=new Object  ;
				stopList.allWords=["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77","78","78","80","81","82","83","84","85","86","87","88","89","90","91","92","93","94","95","96","97","98","99","100","1990","1991","1992","1993","1994","1995","1996","1997","1998","1999","2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020",";",".",",",":","%","&","-","\?","!","\*","@","\+","\(","\)","\]","\[","\{","\}","<",">","$","#","\^","|","a","about","above","across","after","afterwards","again","against","all","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","another","any","anyhow","anyone","anything","anyway","anywhere","are","around","as","at","b","back","be","because","been","before","beforehand","being","beside","besides","between","both","bottom","but","by","c","call","can","cannot","cant","co","con","could","couldnt","d","de","did","didn/'t","do","don/'t","does","doesn/'t","done","down","due","during","e","each","eg","eight","either","eleven","else","elsewhere","enough","etc","even","ever","every","everyone","everything","everywhere","except","f","few","fifteen","fify","fill","find","fire","first","five","for","former","formerly","forty","found","four","from","front","full","further","g","get","give","go","h","had","has","hasnt","have","he","hence","her","here","hereafter","hereby","herein","hereupon","hers","herself","him","himself","his","how","however","hundred","i","ie","if","in","inc","indeed","into","is","it","its","itself","j","k","keep","l","last","latter","latterly","least","less","ltd","m","made","many","may","me","meanwhile","might","mill","mine","more","moreover","most","mostly","move","much","must","my","myself","n","name","namely","neither","never","nevertheless","next","nine","no","nobody","none","noone","nor","not","nothing","now","nowhere","o","of","off","often","on","once","one","only","onto","or","other","others","otherwise","our","ours","ourselves","out","over","own","p","part","per","perhaps","please","put","q","r","rather","re","s","same","see","seem","seemed","seeming","seems","serious","several","she","should","since","six","sixty","so","some","somehow","someone","something","sometime","sometimes","somewhere","still","such","system","t","take","ten","than","that","the","their","them","themselves","then","thence","there","thereafter","thereby","therefore","therein","thereupon","these","they","thing","third","this","those","though","three","through","throughout","thru","thus","to","together","too","toward","towards","twelve","twenty","two","u","un","under","until","up","upon","us","v","very","via","w","was","we","well","were","what","whatever","when","whence","whenever","where","whereafter","whereas","whereby","wherein","whereupon","wherever","whether","which","while","whither","who","whoever","whole","whom","whose","why","will","with","within","without","would","x","y","yet","you","your","yours","yourself","yourselves","z"];
				//List from http://taporware.mcmaster.ca/~taporware/cgi-bin/prototype/glasgowstoplist.txt
				stopList.word = { };
				
				//Stoplist inclusion criteria - when will it be used.
				for (var i in stopList.allWords) {
					//If glasgow stoplist is desired and the tool is not concordances or collocates, include the stoplist
					if (ListTools.selectedItem.label != "Get Concordance" &&  allOptions["stopList"] == "glasgow") {
						stopList.word[stopList.allWords[i]] = true; //true to turn on list, false to turn off
					} else {
						stopList.word[stopList.allWords[i]] = false;
					}
				}
				for (i in wordSplit) {
					var xword = wordSplit[i]; // done only for purposes of readability in below code
					
					//if word already exists in array, add 1 to count
					if (allWords.count[xword]) {
						allWords.count[xword] += 1;
					} 	
					//if word doesn't exists in stop list, create a new entry OR if the current tool is collocates.
					else if (!stopList.word[xword] || ListTools.selectedItem.label == "Collocating Words") {
						allWords.words.push(xword);
						allWords.count[xword] = 1;
						allWords.indexCounts[xword] = [];
					}
					if (!stopList.word[xword] || ListTools.selectedItem.label == "Collocating Words") {
						allWords.orderedArray.push(xword); //adds to index of all words in order
						allWords.indexCounts[xword].push(allWords.orderedArray.length - 1);//adds orderedArray index place to that words's list if index locations
					}
				}

				catBgVisibility(false);
				
				if (ListTools.selectedItem.label == "List Words" || "Word Cloud") {
					dp = new DataProvider();
					for (i in allWords.words) {
						dp.addItem({Word:allWords.words[i],Count:allWords.count[allWords.words[i]],Index:i});
					}
					//dp.sortOn("Index", Array.NUMERIC);
					dp.sortOn("Count", Array.NUMERIC |  Array.DESCENDING );

					//Array.RETURNINDEXEDARRAY |
					//dp.removeItemAt(1);
					//trace ("dp length:" + dp.length);
					
				}

				//Create Datagrid Object of List Words and Collocating Words
				if (ListTools.selectedItem.label == "List Words" || "Collocating Words") {
					dg = new DataGrid ;
					dg.move(datagridPadding + widthDif / 2, (datagridPadding + distanceBetween));
					dg.width=toolWidth-datagridPadding*2;
					dg.height= (toolHeight-(distanceBetween*totalCats+datagridPadding*2));
				}
				
				if (ListTools.selectedItem.label == "List Words") {
					dg.columns=["Word","Count"];
					dg.columns[1].sortOptions = Array.NUMERIC;
					dg.dataProvider=dp;
					dg.minColumnWidth=dg.width*1/3;
					dg.addEventListener(ListEvent.ITEM_CLICK, cellPress);
					Results.addChild(dg);
				} 
				else if (ListTools.selectedItem.label == "Word Cloud") {
					//var testCloud:wordcloud = new wordcloud(dp, toolHeight-(distanceBetween*totalCats), toolWidth, {bg:"#00ff00", textColor:"#ff0000", padding:datagridPadding});
					//Results.backg.addChild(testCloud);
					
					var maxWordCloud = 100;
					while (dp.length > maxWordCloud) dp.removeItemAt(maxWordCloud - 1);

					var totalCloudCount = 0;
					var maxCount = 0; //for knowing the highest occurrence count without any sorting
					for (i = 0; i < dp.length; i++) {
						totalCloudCount +=  dp.getItemAt(i).Count;
						if (dp.getItemAt(i).Count > maxCount) maxCount = dp.getItemAt(i).Count;
					}
					totalCloudCount = totalCloudCount * dp.getItemAt(dp.length-1).Count;
					var maxSize = 300*(dp.getItemAt(0).Count/totalCloudCount);
					dp.sortOn("Index", Array.NUMERIC);
					
					var cloudText1:String="";
					
					for (i=0; i<dp.length; i++) {
						cloudText1 = cloudText1 
						+ " " 
						//+ "<font size='+"+300*(dp.getItemAt(i).Count/totalCloudCount)+"' "+cloudColour(dp.getItemAt(i).Count, maxCount)+">" 
						+ "<font size='+"+300*(dp.getItemAt(i).Count/totalCloudCount)+"' color='"+diffColors(allOptions["background-color"], "#ffffff", maxCount+2, dp.getItemAt(i).Count+2)+"'>" 
						+"<a href=\"event:"+dp.getItemAt(i).Word+"\">"
						+ unescape(dp.getItemAt(i).Word)
						+"</a>"
						+ "</font>" ;
					}
					
					
					cloudText1="<p align='JUSTIFY'><font size='-"+0.2*maxSize+"'>"+cloudText1+"</font></p>";//create List component
					setLabelText(cloudField1, cloudText1, datagridPadding, Results.backg);
					cloudField1.height = (toolHeight-(distanceBetween*totalCats+datagridPadding*2));
					cloudField1.addEventListener(TextEvent.LINK, cloudLinkHandler);

					function diffColors (startColor, endColor, increments, currentIncrement) {
						startColor =  cssToHex (startColor); //converts #123456 format to the 0x123456 hex format used by AS
						endColor = cssToHex (endColor);
						var rDifference = (endColor >> 16 & 0xFF) - (startColor >> 16 & 0xFF); 
						var gDifference = (endColor >> 8 & 0xFF) - (startColor >> 8 & 0xFF);
						var bDifference = (endColor & 0xFF) - (startColor & 0xFF);
						
						var rIncrement = Math.round(rDifference / increments);
						var gIncrement = Math.round(gDifference / increments);
						var bIncrement = Math.round(bDifference / increments);
						
						var currentR = (startColor >> 16 & 0xFF)+(currentIncrement * rIncrement);
						var currentG = (startColor >> 8 & 0xFF)+(currentIncrement * gIncrement);
						var currentB = (startColor & 0xFF)+(currentIncrement * bIncrement);
						
						return ("#" + d2h(currentR) + d2h(currentG) + d2h(currentB)) //spit out an HTML-like #123456 format
					}

					
				default xml namespace=new Namespace("");//based on strange error noted here: http://www.adnandoric.com/2009/03/verifyerror-error-1025-an-invalid-register-3-was-accessed/
			} 
				else if (ListTools.selectedItem.label == "Get Concordance") {
					//patternSelect.text="nickel"; //for testing
					//test concordances
					if (patternSelect.text) {
						CategoriesArray["Results"].title = "Results for : " + patternSelect.text;
						Results.catBar.catTXT.text=CategoriesArray["Results"].title;
						var concordancesArray:Object = new Object;
						if (concordanceStyle == "grid") dp = new DataProvider();
						else if (concordanceStyle == "text") concordanceText = "";
						concordancesArray.wordIndex = { };
						for (i in allWords.indexCounts[patternSelect.text]) { //for every instance of patternSelect.text
								var wordLoc= allWords.indexCounts[patternSelect.text.toLowerCase()][i];
								concordancesArray.wordIndex[wordLoc] = { }; //creates an entry named after the OrderedArray index location
								concordancesArray.wordIndex[wordLoc].before = "";
								concordancesArray.wordIndex[wordLoc].after = "";
								for (var j = 0; j < 5; j++) {
									if (wordLoc-1-j >= 0) concordancesArray.wordIndex[wordLoc].before = allWords.orderedArray[wordLoc-1-j] + " " + concordancesArray.wordIndex[wordLoc].before;
								}
								for (j = 0; j < 5; j++)	{
									if (wordLoc+1+j <= allWords.orderedArray.length) concordancesArray.wordIndex[wordLoc].after = concordancesArray.wordIndex[wordLoc].after + allWords.orderedArray[wordLoc+1+j]+" ";
								}
								concordanceField.width = toolWidth-datagridPadding*2;
								if (concordanceStyle == "grid") {
									dp.addItem( {
										Before:concordancesArray.wordIndex[wordLoc].before, 
										Word:patternSelect.text, 
										After:concordancesArray.wordIndex[wordLoc].after, 
										Index:i
										});
									//trace ("concordance" + concordancesArray.wordIndex[wordLoc].before +"//" + patternSelect.text + "//" + concordancesArray.wordIndex[wordLoc].after);
								} 
								else if (concordanceStyle == "text") {
									concordanceText  = concordanceText 
									+"<p width='"+concordanceField.width+"' align='left'><font size='-0'><span>"+concordancesArray.wordIndex[wordLoc].before
									+"</p><p width='"+concordanceField.width+"' align='center'><font type='Arial, Helvetica' size='+4'>" + patternSelect.text + "</font></p><p width='"+concordanceField.width+"' align='right'>"
									+" " +concordancesArray.wordIndex[wordLoc].after + "</font></p><br /><br />";//create List component
								}
						}	
							if (concordanceStyle == "grid") {
								dg=new DataGrid;
								dg.move(datagridPadding+widthDif/2,(datagridPadding+distanceBetween));
								dg.width=toolWidth-datagridPadding*2;
								dg.height= (toolHeight-100-(distanceBetween*totalCats+datagridPadding*2));
								dg.columns=["Before", "Word","After"];
								dg.dataProvider=dp;
								Results.addChild(dg);
							} 
							else if (concordanceStyle == "text") {
								setLabelText(concordanceField, concordanceText, datagridPadding, Results.backg);
								/*if ( concordanceField.width < 500 ) {
									concordanceField.width = 500;
									concordanceField.x = (toolWidth - concordanceField.width) / 2;
								}*/
								
								concordanceField.height = (toolHeight - (distanceBetween * totalCats + datagridPadding * 2));
								//concordanceField.background = true;
								//concordanceField.backgroundColor = 0x444444;
								
								sb = new UIScrollBar();
								concordanceField.width -= sb.width/2;
								sb.move(concordanceField.x + concordanceField.width, concordanceField.y);
								sb.height = concordanceField.height;
								sb.setSize(concordanceField.width, concordanceField.height);
								sb.scrollTarget = concordanceField;
								Results.backg.addChild(sb);    
								
								/*var concordanceField2:TextField = new TextField();
								concordanceField2.wordWrap = true;
								concordanceField2.multiline = true;
								var concordanceText2 = "This is a test";
								concordanceField2.background = true;
								concordanceField2.backgroundColor = 0x555555;
								setLabelText(concordanceField2, concordanceText2, datagridPadding, Results.backg);
								concordanceField2.height = (100 - (datagridPadding * 2));
								concordanceField2.y += concordanceField.height + concordanceField.y + datagridPadding;
								concordanceField2.addEventListener(TextEvent.LINK, concordanceLinkHandler);*/
							}
								
								/*var tf2:TextFormat = new TextFormat();
								tf2.bold = true;
								tf2.color = 0xFFFFFF;
								dg.columns[0].setRendererStyle("textFormat",tf2);
								*/
								/*var concordanceField:TextField = new TextField();
								concordanceField.multiline=true;
								concordanceField.wordWrap = true;
								concordanceField.height=100;
								concordanceField.background=true;
								concordanceField.border=true;
								concordanceField.width=toolWidth-datagridPadding*2;
								concordanceField.x=datagridPadding+dg.height;
								//concordanceField.y=datagridPadding;
								concordanceField.y = 0;
								concordanceField.antiAliasType=AntiAliasType.ADVANCED;
								concordanceField.htmlText="pigeon, puppy, piglet, pig, pumpkin, pine cone, quarter, queen, Roo, robot, rabbit, rock, star, snail, snake, snow, spider, spoon, tree, table, train, tractor, umbrella, violin, van, world, water, wagon, winnie the pooh, xylophone, x-ray, yo-yo, yellow, yarn, zebra, zoo, zipper,";
								Results.addChild(concordanceField);*/
					}
				} 
				else if (ListTools.selectedItem.label == "Collocating Words") {
					//patternSelect.text="ulysses"; for testing
					//test collocates
					CategoriesArray["Results"].title = "Results for : " + patternSelect.text;
					Results.catBar.catTXT.text=CategoriesArray["Results"].title;
					if (patternSelect.text) {
						var collocatesArray:Object=new Object;
						collocatesArray.words = []; //Array of all the collocating words
						collocatesArray.wordIndex = { }; //Objects for each word. If wordIndex[xxx] exists, then we know that it's been added to the words Array
						for (i in allWords.indexCounts[patternSelect.text.toLowerCase()]) { //for every instance of patternSelect.text
							
							//trace(allWords.indexCounts[patternSelect.text.toLowerCase()][i]);
							var currentIndex = allWords.indexCounts[patternSelect.text.toLowerCase()][i];
							
							//Checks if the word has already been added to the list of collocating words (wordIndex)
							//First checks the word before (if there is a word before)...
							if (currentIndex > 0) {
								var wordBefore = allWords.orderedArray[currentIndex - 1];
								if (!collocatesArray.wordIndex[wordBefore] && !stopList.word[wordBefore]) {
										collocatesArray.words.push(wordBefore);
										collocatesArray.wordIndex[wordBefore] = true;
								}
							}
							//..Then checks the word after (if there is a word after)
							if (currentIndex < (allWords.orderedArray.length - 1)) {
								var wordAfter = allWords.orderedArray[currentIndex + 1];
								//Note that stoplist wasn't used before, so that you could search 
								//by common words, but it is used for display
								if (!collocatesArray.wordIndex[wordAfter] && !stopList.word[wordAfter]) {
									collocatesArray.words.push(wordAfter);
									collocatesArray.wordIndex[wordAfter] = true;
								}
							}
						};
						trace ("collocates(" + collocatesArray.words.length + "): " + collocatesArray.words);
						//dg.columns=["Collocate","SpanFrequency","TextFrequency","ZScore"];
						//dg.minColumnWidth=dg.width*1 / 3;
						dg.columns=["Collocate","Frequency"];
						dg.columns[1].sortOptions = Array.NUMERIC;
						//dg.dataProvider=dp;
						dg.addEventListener(ListEvent.ITEM_CLICK, cellPress);
						for (i = 0; i < collocatesArray.words.length; i++) {
							sampleItem=
							{
							Collocate: collocatesArray.words[i],
							Frequency: allWords.count[collocatesArray.words[i]]
							//SpanFrequency:TAPORresult.item[i].spanfrequency,
							//TextFrequency:TAPORresult.item[i].textfrequency,
							//ZScore:TAPORresult.item[i]["z-score"]
							};

							//dg.columns[1].visible=false;
							//dg.columns[2].visible=false;
							//dg.columns[3].visible=true;
							
							dg.columns[0].sortOptions = Array.DESCENDING;
							dg.columns[1].sortOptions = Array.NUMERIC;
							//dg.columns[2].sortOptions = Array.NUMERIC;
							//dg.columns[3].sortOptions = Array.NUMERIC;
							//dp.sortOn("Count", Array.NUMERIC |  Array.DESCENDING );
							
							dg.addItem(sampleItem);
							Results.addChild(dg);
						}
					}
				}
			}
		}
	}
function cloudLinkHandler(e:TextEvent):void {
		ListTools.selectedIndex=3;//index position of collocating words in "Choose Tool" list. Should be done much more cleanly.
		patternSelect.text=e.text;
		slidingSetup(CategoriesArray["Results"].position);
		CategoriesArray["Results"].title = "Results";
		Results.catBar.catTXT.text=CategoriesArray["Results"].title;
		CategoriesArray["tool"].title="Tool : "+ListTools.selectedItem.label;
		tool.catBar.catTXT.text=CategoriesArray["tool"].title;
		NavigateToURLcss();
			}
function concordanceLinkHandler(e:TextEvent):void {
		ListTools.selectedIndex=3;//index position of collocating words in "Choose Tool" list. Should be done much more cleanly.
		patternSelect.text=e.text;
		slidingSetup(CategoriesArray["Results"].position);
		CategoriesArray["Results"].title = "Results for : " + patternSelect.text;
		Results.catBar.catTXT.text=CategoriesArray["Results"].title;
		CategoriesArray["tool"].title="Tool : "+ListTools.selectedItem.label;
		tool.catBar.catTXT.text=CategoriesArray["tool"].title;
		NavigateToURLcss();
			}
function cleanTags(inputText) {
	//Note: due to complexity of regular expression it is iteratively broken up and commented below
	var cleaningExpression = "<head\\b[^>]*>(((?!<\/?head).)*)<\/head>" //remove head tag and content
	+"|" +"<(script|style)\\b[^>]*>(((?!<\/?(script|style)).)*)<\/(script|style)>" //remove script/style tags and their content
	+"|" +"<\/?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)\/?>" //remove any html tags
	+"|" +"(\\<|<)!--\s*.*?\\s*--(\\&gt;|>)" //remove HTML comments
	+"|" +"&(nbsp);";//remove non breaking stops
	var removeTagsExp:RegExp=new RegExp(cleaningExpression,"gis");
	//var removeTagsExp:RegExp=new RegExp("<\/?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)\/?>","g");
	//var removeTagsExp:RegExp=new RegExp("<[^<]+?>","g");
	var wordClean=inputText.replace(removeTagsExp,"");
	return wordClean;
}
function splitWords(inputText) {//splits up string into array of lowercase words
	inputText=inputText.toLowerCase();
	trace (inputText);
	var specialChars = "|à|á|â|ã|ä|å|æ|ç|è|é|ê|ë|ì|í|î|ï|ð|ñ|ò|ó|ô|õ|ö|ø|ù|ú|û|ü|ý|ÿ";
	var splitWordsExp:RegExp=new RegExp("\\b([\\w"+specialChars+"]+)([-]?)([\\'\\w"+specialChars+"]*)\\b","g");
	var wordSplit:Array=inputText.match(splitWordsExp);
	return wordSplit;
}
function processData(event:Event):void {
	setLabelText(cloudField1, " ", datagridPadding, Results.backg);
	if (currentCat==CategoriesArray["Results"].position) {
		catBgVisibility(false);
		trace("TAPORresult: " + event.target.data);
		if (event.target.data) {
		}
		TAPORresult=XML(event.target.data);
		//trace ("TAPORresult: " + TAPORresult);
		//define namespace
		var TAPOR:Namespace=TAPORresult.namespace("tapor");
		default xml namespace=TAPOR;
		if (ListTools.selectedItem.label=="Old List Words"||ListTools.selectedItem.label=="Old Get Concordance"||ListTools.selectedItem.label=="Old Collocating Words") {
			dg=new DataGrid  ;
			dg.move(datagridPadding+widthDif/2,(datagridPadding+distanceBetween));
			dg.width=toolWidth-datagridPadding*2;
			dg.height= (toolHeight-(distanceBetween*totalCats+datagridPadding*2));
			if (TAPORresult.item.length()==0) {
				//trace("uh oh");
				dg.columns=["Sorry, there were no results."];
				addChild(dg);
				return;
			}
			if (ListTools.selectedItem.label=="Old List Words") {
				dg.columns=["Word","Count"];
				dg.columns[1].sortOptions = Array.NUMERIC;
				dg.minColumnWidth=dg.width*1/3;
				for (i=0; i<TAPORresult.item.length(); i++) {
					sampleItem={Word:TAPORresult.item[i].label,Count:TAPORresult.item[i].count};
					dg.addItem(sampleItem);
				}
				dg.addEventListener(ListEvent.ITEM_CLICK, cellPress);
			}
			if (ListTools.selectedItem.label=="Old Get Concordance") {
				dg.columns=["Before","Pattern","After"];
				for (i=0; i<TAPORresult.item.length(); i++) {
					sampleItem=
					{
					Before:TAPORresult.item[i].text()[0],
					Pattern:TAPORresult.item[i].pattern.B,
					After:TAPORresult.item[i].text()[1]
					};
					//trace (TAPORresult.item[i].pattern);
					dg.addItem(sampleItem);
				}
			}
			if (ListTools.selectedItem.label=="Old Collocating Words") {
				dg.columns=["Collocate","SpanFrequency","TextFrequency","ZScore"];
				//dg.minColumnWidth=dg.width*1 / 3;
				for (i=0; i<TAPORresult.item.length(); i++) {
					sampleItem=
					{
					Collocate:TAPORresult.item[i].collocate,
					SpanFrequency:TAPORresult.item[i].spanfrequency,
					TextFrequency:TAPORresult.item[i].textfrequency,
					ZScore:TAPORresult.item[i]["z-score"]
					};

					dg.columns[1].visible=false;
					dg.columns[2].visible=false;
					dg.columns[3].visible=true;
					
					dg.columns[0].sortOptions = Array.DESCENDING;
					dg.columns[1].sortOptions = Array.NUMERIC;
					dg.columns[2].sortOptions = Array.NUMERIC;
					dg.columns[3].sortOptions = Array.NUMERIC;
					//dp.sortOn("Count", Array.NUMERIC |  Array.DESCENDING );
					
					dg.addItem(sampleItem);

				}
			}
			Results.addChild(dg);
			default xml namespace=new Namespace("");
			trace("Datagrid created successfully (x,y,toolHeight,distanceBetween) :" + dg.x+dg.y+toolHeight+distanceBetween);
		} else if (ListTools.selectedItem.label=="Old Word Cloud") {
			var cloudText1:String="";
			for (i=0; i<TAPORresult.item.length(); i++) {
				cloudText1 = cloudText1 + " " + "<font size='+"+(3*TAPORresult.item[i].count)+"'>" + TAPORresult.item[i].label + "</font>" ;
			}
			cloudText1="<font size='-"+Math.round(TAPORresult.summary[0].count[1]/40)+"'>"+cloudText1+"</font>";//create List component
			setLabelText(cloudField1, cloudText1, datagridPadding, Results.backg);
			cloudField1.height = (toolHeight-(distanceBetween*totalCats+datagridPadding*2));
		}
	}
}
function cellPress(e:ListEvent) {
	if (e.columnIndex==0) {
		ListTools.selectedIndex=3;//index position of collocating words in "Choose Tool" list. Should be done much more cleanly.
		patternSelect.text=dg.getItemAt(e.rowIndex.toString()).Word;
		slidingSetup(CategoriesArray["Results"].position);
		CategoriesArray["tool"].title="Tool : "+ListTools.selectedItem.label;
		tool.catBar.catTXT.text=CategoriesArray["tool"].title;
		NavigateToURLcss();
		trace(dg.getItemAt(e.rowIndex.toString()).Word);
	}
}